package com.uduemc.biso.node.web.component.html;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.HtmlUtils;

import com.uduemc.biso.node.core.common.sysconfig.DownloadSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.downloadsysconfig.DownloadSysListConfig;
import com.uduemc.biso.node.core.common.sysconfig.downloadsysconfig.DownloadSysListTextConfig;
import com.uduemc.biso.node.core.common.udinpojo.PagingData;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SDownloadAttr;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.entities.custom.Download;
import com.uduemc.biso.node.core.entities.custom.DownloadAttrAndContent;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.web.component.SiteUrlComponent;
import com.uduemc.biso.node.web.component.html.common.HCPagingUdin;
import com.uduemc.biso.node.web.component.html.common.SystemListCrumbs;
import com.uduemc.biso.node.web.component.html.common.SystemListSearch;

import cn.hutool.core.util.StrUtil;

@Component
public class HSystemDownloadItemListUdin {

	private static String name = "system_download_item_list";

	@Autowired
	private BasicUdin basicUdin;

	@Autowired
	private SiteUrlComponent siteUrlComponent;

	@Autowired
	private HCPagingUdin hCPagingUdin;

	@Autowired
	private SystemListCrumbs systemListCrumbs;

	@Autowired
	private SystemListSearch systemListSearch;

	public StringBuilder html(DownloadSysConfig downloadSysConfig, SPage page, SCategories category, List<SDownloadAttr> listSDownloadAttr,
			List<Download> listDownload, List<SCategories> listSCategories, String keyword, int pageNum, int total, int pageSize) throws IOException {
		if (downloadSysConfig == null || page == null) {
			return new StringBuilder("<!-- DownloadLComp empty downloadSysConfig -->\n");
		}
		DownloadSysListConfig downloadSysListConfig = downloadSysConfig.getList();
		DownloadSysListTextConfig downloadSysListTextConfig = downloadSysConfig.getLtext();
		// 通过系统id 制作唯一编码
		String md5Id = DigestUtils.md5DigestAsHex(String.valueOf(page.getId()).getBytes());

		int tableStyle = downloadSysListConfig.getListstyle();

		// 顶部class
		String topClass = getTopClass(downloadSysListConfig);

		// 制作面包屑
		// crumbs
		List<SCategories> list = new ArrayList<>();
		idList(list, listSCategories, category != null ? category.getId() : null);
		// 反转链表
		Collections.reverse(list);
		String crumbs = crumbs(downloadSysConfig, page, list);

		// 搜索
		String search = search(downloadSysConfig, keyword, md5Id);

		// font-size
		String tableTagStyle = tableTagStyle(downloadSysConfig);

		// 分页部分
		String listHref = siteUrlComponent.getListHref(page, category, "[page]", keyword);
		PagingData pagingData = downloadSysConfig.getLtext().getPagingData();
		int pageTotal = (int) Math.ceil((double) total / (double) pageSize);
		// pagging
		StringBuilder pagging = hCPagingUdin.html(listHref, pageNum, pageTotal, pagingData);

		// 填充下载列表信息
		fillDownloadInfo(downloadSysConfig, listDownload, listSDownloadAttr, pageNum, pageSize);

		// 文本没有数据
		String noData = HtmlUtils.htmlEscape(downloadSysListTextConfig.getNoData());

		// 每行显示文件数
		String pageColumnStyle = pageColumnStyle(downloadSysConfig);

		// 下载链接处显示文本的时候的默认文本内容
		String downloadDt = downloadSysListTextConfig.getDownloadt();

		// 下载图标样式
		Map<String, String> iconClassMap = getIconClassMap();

		// 生成html渲染内容
		StringBuilder stringBuilder = new StringBuilder("<!-- DownloadLComp -->\n");

		Map<String, Object> mapData = new HashMap<>();
		mapData.put("topClass", topClass);
		mapData.put("crumbs", crumbs);
		mapData.put("search", search);
		mapData.put("tableTagStyle", tableTagStyle);
		mapData.put("pageColumnStyle", pageColumnStyle);
		mapData.put("downloadDt", downloadDt);
		mapData.put("iconClassMap", iconClassMap);
		mapData.put("noData", noData);
		mapData.put("attrList", listSDownloadAttr);
		mapData.put("dataList", listDownload);
		mapData.put("pagging", pagging.toString());

		StringWriter render = basicUdin.render(name, "default_" + tableStyle, mapData);
		stringBuilder.append(render);

		return stringBuilder;
	}

	public void fillDownloadInfo(DownloadSysConfig downloadSysConfig, List<Download> listDownload, List<SDownloadAttr> listSDownloadAttr, int pageNum,
			int pageSize) {
		if (downloadSysConfig == null || CollectionUtils.isEmpty(listDownload) || CollectionUtils.isEmpty(listSDownloadAttr)) {
			return;
		}

		int tableStyle = downloadSysConfig.getList().getListstyle();

		// 下载显示样式
		int downloadStyle = downloadSysConfig.getList().getDownloadstyle();

		// 下载链接处显示文本的时候的默认文本内容
		String downloadDt = downloadSysConfig.getLtext().getDownloadt();

		String onlineBrowseText = downloadSysConfig.getLtext().getOnlineBrowseText();

		long number = pageNum < 1 ? 0 : (pageNum - 1) * pageSize;
		for (Download download : listDownload) {
			number++;
			List<DownloadAttrAndContent> attrAndContentList = download.getListDownloadAttrAndContent();
			for (DownloadAttrAndContent attrAndContent : attrAndContentList) {
				SDownloadAttr sDownloadAttr = attrAndContent.getSDownloadAttr();
				if (sDownloadAttr.getIsShow() == 0) {
					continue;
				}
				String content = "";
				switch (sDownloadAttr.getType()) {
				case 0:// 自定义内容
					if (attrAndContent.getSDownloadAttrContent() != null)
						content = attrAndContent.getSDownloadAttrContent().getContent();
					attrAndContent.setContent(content);
					break;
				case 1:// 序号
					content = String.valueOf(number);
					attrAndContent.setContent(content);
					break;
				case 2:// 分类名称
					if (download.getCategoryQuote() != null && download.getCategoryQuote().getSCategories() != null) {
						SCategories sCategories = download.getCategoryQuote().getSCategories();
						if (!StringUtils.isEmpty(sCategories.getName())) {
							content = sCategories.getName();
						}
					}
					attrAndContent.setContent(content);
					break;
				case 3:// 下载文件名称
					content = attrAndContent.getSDownloadAttrContent().getContent();
					attrAndContent.setContent(content);
					break;
				case 4:
					// 下载文件链接
					RepertoryQuote fileRepertoryQuote = download.getFileRepertoryQuote();
					if (fileRepertoryQuote == null || fileRepertoryQuote.getHRepertory() == null) {
						continue;
					}
					HRepertory hRepertory = fileRepertoryQuote.getHRepertory();
					String downloadHref = siteUrlComponent.getDownloadHref(hRepertory.getId());

					if (tableStyle >= 1 && tableStyle <= 3) {
//						#if($downloadStyle == 1)
//							<a href="$attrAndContent.content" target="_blank" class="aHovercolor_main"><i class="$iconClassMap.get($item.fileRepertoryQuote.hRepertory.suffix)"></i></a>
//						#else
//							<a href="$attrAndContent.content" target="_blank" class="aHovercolor_main">$downloadDt</a>
//						#end
						StringBuffer html = new StringBuffer();
						String suffix = hRepertory.getSuffix();
						if (downloadStyle == 1) {
							if (suffix.toLowerCase().equals("pdf")) {
								String onlineBrowseHref = siteUrlComponent.getPreviewPdfHref(hRepertory.getOriginalFilename(), hRepertory.getId());
								html.append("<a href=\"" + onlineBrowseHref
										+ "\" target=\"_blank\" class=\"aHovercolor_main\"><img style=\"width: 25px;height: 25px;\" src=\"/assets/static/site/np_template/images/icon_preview1.png\" /></a>&nbsp;&nbsp;");
							}
							// 图标
							String iconClass = getIconClassMap(suffix);
							html.append(
									"<a href=\"" + downloadHref + "\" target=\"_blank\" class=\"aHovercolor_main\"><i class=\"" + iconClass + "\"></i></a>");
						} else {
							if (suffix.toLowerCase().equals("pdf")) {
								String onlineBrowseHref = siteUrlComponent.getPreviewPdfHref(hRepertory.getOriginalFilename(), hRepertory.getId());
								html.append("<a href=\"" + onlineBrowseHref + "\" target=\"_blank\" class=\"aHovercolor_main\">" + onlineBrowseText + "</a>&nbsp;&nbsp;");
							}
							// 文字
							html.append("<a href=\"" + downloadHref + "\" target=\"_blank\" class=\"aHovercolor_main\">" + downloadDt + "</a>");
						}
						attrAndContent.setContent(html.toString());
					} else if (tableStyle >= 4 && tableStyle <= 6) {
						attrAndContent.setContent(downloadHref);
					} else {
						attrAndContent.setContent(content);
					}

					break;
				}
			}
		}
	}

	/**
	 * 制作搜索栏目
	 *
	 * @param downloadSysConfig
	 * @param keyword
	 * @param md5Id
	 * @return
	 */
	protected String search(DownloadSysConfig downloadSysConfig, String keyword, String md5Id) {
		DownloadSysListConfig downloadSysListConfig = downloadSysConfig.getList();
		int showSearch = downloadSysListConfig.getShowSearch();
		DownloadSysListTextConfig downloadSysListTextConfig = downloadSysConfig.getLtext();
		StringBuilder stringBuilder = new StringBuilder();
		if (showSearch == 0) {
			return "";
		}
		String lanSearch = HtmlUtils.htmlEscape(downloadSysListTextConfig.getLanSearch());
		String lanSearchInput = HtmlUtils.htmlEscape(downloadSysListTextConfig.getLanSearchInput());
		String searchId = "search-" + md5Id;
		String inputId = "input-" + md5Id;
		if (StrUtil.isBlank(keyword)) {
			keyword = "";
		}

		stringBuilder = systemListSearch.render(searchId, inputId, lanSearch, lanSearchInput, keyword);
		return stringBuilder.toString();
	}

	/**
	 * 制作面包屑
	 *
	 * @param downloadSysConfig
	 * @param page
	 * @param list
	 * @return
	 */
	protected String crumbs(DownloadSysConfig downloadSysConfig, SPage page, List<SCategories> list) {
		DownloadSysListTextConfig ltext = downloadSysConfig.getLtext();
		DownloadSysListConfig listDownloadSysListConfig = downloadSysConfig.getList();
		int crumbslasttext = listDownloadSysListConfig.getCrumbslasttext();

		String yourCurrentLocation = HtmlUtils.htmlEscape(ltext.getYourCurrentLocation());
		StringBuilder stringBuilder = systemListCrumbs.render(yourCurrentLocation, crumbslasttext, page, list);

		return stringBuilder.toString();
	}

	/**
	 * 通过左右、或者是上下结构确定顶部的class
	 *
	 * @param downloadSysListConfig
	 * @return
	 */
	protected static String getTopClass(DownloadSysListConfig downloadSysListConfig) {
		int listStructure = downloadSysListConfig.getStructure();
		if (listStructure == 2) {
			// 左右结构的时候
			return "side_left";
		}
		return "";
	}

	/**
	 * 通过 categoryId 以及递归的方式获取 listSCategories 数据中全部的父级数据，然後加入到 list 链表中
	 *
	 * @param list
	 * @param listSCategories
	 * @param categoryId
	 */
	protected static void idList(List<SCategories> list, List<SCategories> listSCategories, Long categoryId) {
		if (categoryId == null || categoryId.longValue() < 1) {
			return;
		}
		for (SCategories sCategories : listSCategories) {
			if (categoryId.longValue() == sCategories.getId().longValue()) {
				list.add(sCategories);
				if (sCategories.getParentId() != null && sCategories.getParentId().longValue() > 0) {
					idList(list, listSCategories, sCategories.getParentId());
				}
				break;
			}
		}
	}

	/**
	 * 通过 Download 获取该数据的分类数据名称，如果没有返回 "" 字串
	 *
	 * @param download
	 * @return
	 */
	protected static String categoryName(Download download) {
		if (download == null || download.getCategoryQuote() == null || download.getCategoryQuote().getSCategories() == null) {
			return "";
		}

		SCategories sCategories = download.getCategoryQuote().getSCategories();
		if (StringUtils.isEmpty(sCategories.getName())) {
			return "";
		}

		return HtmlUtils.htmlEscape(StringUtils.trimAllWhitespace(sCategories.getName()));
	}

	public static String getIconClassMap(String suffix) {
		Map<String, String> iconClassMap = getIconClassMap();
		return iconClassMap.get(suffix.toLowerCase());
	}

	public static Map<String, String> getIconClassMap() {
		Map<String, String> iconClassMap = new HashMap<>();
		iconClassMap.put("doc", "icon_file icon_file1");
		iconClassMap.put("docx", "icon_file icon_file1");
		iconClassMap.put("pdf", "icon_file icon_file2");
		iconClassMap.put("zip", "icon_file icon_file3");
		iconClassMap.put("rar", "icon_file icon_file3");
		iconClassMap.put("xls", "icon_file icon_file4");
		iconClassMap.put("xlsx", "icon_file icon_file4");
		iconClassMap.put("txt", "icon_file icon_file5");
		iconClassMap.put("ppt", "icon_file icon_file6");

		return iconClassMap;
	}

	/**
	 * 获取table 标签的 style 样式
	 *
	 * @return
	 */
	public static String tableTagStyle(DownloadSysConfig downloadSysConfig) {
		if (downloadSysConfig == null) {
			return "";
		}
		DownloadSysListConfig list = downloadSysConfig.getList();
		if (list == null) {
			return "";
		}
		String fontSize = list.getFontsize();
		if (StringUtils.hasText(fontSize)) {
			return "font-size: " + fontSize + ";";
		}
		return "";
	}

	public static String pageColumnStyle(DownloadSysConfig downloadSysConfig) {
		if (downloadSysConfig == null) {
			return "";
		}
		DownloadSysListConfig list = downloadSysConfig.getList();
		if (list == null) {
			return "";
		}
		int pageColumns = list.getPagecolumns();
		if (pageColumns > 1) {
			return "listLiX" + pageColumns;
		}
		return "";
	}
}